package com.dzwww.recommend.rule.util.validator;

import com.dzwww.recommend.rule.common.api.ApiException;
import com.dzwww.recommend.rule.common.constant.CommonErrorMessage;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *  校验工具
 * <p>
 *   @author lixin
 *   @date 2018/4/9 下午1:58
 *   @version 1.0
 */
public class ValidatorUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 验证
     *
     * @param obj   验证的对象
     * @param group 验证的分组
     * @param <T>   <T>
     * @return 错误结果
     */
    public static <T> Map<String, StringBuffer> validate(T obj, Class... group) {
        Map<String, StringBuffer> errorMap = null;

        if (Objects.isNull(obj)) {
            errorMap = new HashMap<>(1);
            errorMap.put("error", new StringBuffer("传入对象不能为空"));
            return errorMap;
        }

        Set<ConstraintViolation<T>> set;

        if (group == null || group.length == 0) {
            set = validator.validate(obj, Default.class);
        } else {
            set = validator.validate(obj, group);
        }

        if (set != null && set.size() > 0) {
            errorMap = new HashMap<>(5);
            String property;
            for (ConstraintViolation<T> cv : set) {
                //这里循环获取错误信息，可以自定义格式
                property = cv.getPropertyPath().toString();
                if (errorMap.get(property) != null) {
                    errorMap.get(property).append(",").append(cv.getMessage());
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }

        return errorMap;
    }

    /**
     * 验证的错误信息转化为异常
     *
     * @param obj   验证的对象
     * @param group 验证的分组
     * @param <T>   <T>
     * @throws ApiException ApiException
     */
    public static <T> void validateParseException(T obj, Class... group) throws ApiException {
        Map<String, StringBuffer> validateMap = validate(obj, group);
        if (MapUtils.isNotEmpty(validateMap)) {
            String errorMsg = validateMap.entrySet().iterator().next().getValue().toString();
            throw CommonErrorMessage.VERIFY_ERROR.addMsg(errorMsg).toException();
        }
    }

}
